import { useUserStore } from "@/store";
import nimApi from "@/api/nim";
import { IMUIKit } from "@xkit-yx/im-kit-ui";
import NIM, { V2NIMConst } from "nim-web-sdk-ng";
import router from "@/router";
import {
  V2NIMCreateTeamParams,
  V2NIMTeamType,
} from "nim-web-sdk-ng/dist/esm/nim/src/V2NIMTeamService";

export const useNimStore = defineStore("Nim", () => {
  const userStore = useUserStore();
  /*nim登录信息*/
  const nimInfo = ref({ token: "", accountId: "" });
  /*会话列表*/
  const conversationList = ref([]);
  /*接收人*/
  const receiverAccount = ref();
  /*会话ID*/
  const conversationId = ref();
  /*当前活动的的消息列表*/
  const messageList = ref([]);
  /*未读消息*/
  const unreadMessageCount = ref(0);
  /*nim实例*/
  let nimInstance: NIM = undefined;
  /*UI工具实例*/
  let uikit: IMUIKit = undefined;
  const permission = ref(Notification.permission); // 记录通知权限状态

  const localOptions = {
    // 添加好友模式，默认需要验证
    addFriendNeedVerify: false,
    // 群组被邀请模式，默认不需要验证
    teamAgreeMode: V2NIMConst.V2NIMTeamAgreeMode.V2NIM_TEAM_AGREE_MODE_NO_AUTH,
    // 单聊消息是否显示已读未读 默认 false
    p2pMsgReceiptVisible: false,
    // 群聊消息是否显示已读未读 默认 false
    teamMsgReceiptVisible: false,
    // 是否需要@消息 默认 true
    needMention: true,
    enableTeam: true,
    // 是否显示在线离线状态 默认 true
    loginStateVisible: false,
    // 是否允许转让群主
    allowTransferTeamOwner: true,
    aiVisible: false,
  };
  /*获取会话列表*/
  async function getConversationList(params) {
    try {
      const result = await nimInstance.V2NIMConversationService.getConversationList(0, 100);
      console.log("获取会话列表", result);
    } catch (err) {
      console.log("获取会话列表err", err);
    }
  }

  /**
   * 创建群聊
   */
  async function createTeam({ createTeamParams, inviteeAccountIds, serverExtension }) {
    try {
      const params: V2NIMCreateTeamParams = {
        ...createTeamParams,
        serverExtension,
        teamType: V2NIMConst.V2NIMTeamType.V2NIM_TEAM_TYPE_ADVANCED, //群组类型。
        agreeMode: V2NIMConst.V2NIMTeamAgreeMode.V2NIM_TEAM_AGREE_MODE_NO_AUTH, // 不要去同意
      };
      return await nimInstance.V2NIMTeamService.createTeam(params, inviteeAccountIds);
    } catch (e) {
      console.log(e);
      throw e; // 重新抛出错误
    }
  }

  /**
   * 解散群聊
   * @param teamId
   * @param teamType
   */
  async function dismissTeam(
    teamId: string,
    teamType: V2NIMTeamType = V2NIMConst.V2NIMTeamType.V2NIM_TEAM_TYPE_ADVANCED
  ) {
    try {
      await nimInstance.V2NIMTeamService.dismissTeam(teamId, teamType);
    } catch (e) {
      console.log(e);
      throw e; // 重新抛出错误
    }
  }

  /**
   * 获取指定的单个群组信息。
   * @param teamId
   * @param teamType
   */
  async function getTeamInfo(
    teamId: string,
    teamType: V2NIMTeamType = V2NIMConst.V2NIMTeamType.V2NIM_TEAM_TYPE_ADVANCED
  ) {
    try {
      return await nimInstance.V2NIMTeamService.getTeamInfo(teamId, teamType);
    } catch (e) {
      console.log(e);
      throw e; // 重新抛出错误
    }
  }

  /**
   * 获取聊天记录
   * @param params.pageNum
   * @param params.pageSize
   * @param params.conversationId
   * @param params.startTime
   * @param params.endTime
   */
  async function getChatHistoryList(params) {
    try {
      const { list } = await nimApi.getChatHistoryApi({
        pageNum: 1,
        pageSize: 10,
        conversationId: conversationId.value,
        ...params,
      });
      /*const result = await nimApi.getChatHistoryByYxApi({
        pageNum: 1,
        pageSize: 10,
        conversationId: conversationId.value,
        ...params,
      });*/
      console.log("从服务端获取的聊天记录", list);
      messageList.value = list;
    } catch (e) {
      console.log(e);
    }
  }

  /**
   * 同步聊天记录
   * @param params
   */
  async function syncChatHistoryList(params) {
    try {
      const result = await nimApi.syncChatHistoryApi({
        conversationId: conversationId.value,
        ...params,
      });
      console.log("result", result);
    } catch (e) {
      console.log(e);
    }
  }

  /**
   * 删除聊天记录
   * @param params
   */
  async function deleteChatHistoryList(params) {
    try {
      const result = await nimApi.syncRemoveChatHistoryApi({
        conversationId: conversationId.value,
        ...params,
      });
      console.log("result", result);
    } catch (e) {
      console.log(e);
    }
  }

  /*标记会话已读
   */
  async function markConversationRead(conversationId) {
    try {
      await nimInstance.V2NIMConversationService.markConversationRead(conversationId);
    } catch (e) {
      console.log(e);
    }
  }
  /*同步会话列表*/
  async function syncConversation(conversationId) {
    try {
      await nimApi.syncConversationApi({ conversationId });
    } catch (e) {
      console.log(e);
    }
  }
  /*获取当前用户的im token*/
  async function getUserInfo() {
    try {
      const { data } = await nimApi.getByLoginApi({
        userId: userStore.userInfo.userId,
        terminal: "MERCHANT",
      });
      if (data?.token) {
        nimInfo.value.token = data.token;
        nimInfo.value.accountId = data.accountId;
        await initNim();
        await login();
      } else {
        ElMessage.error("获取im用户信息失败");
      }
    } catch (e) {
      ElMessage.error("获取im用户信息失败");
      console.log(e);
    }
  }

  /**
   * 发送消息
   * @param message 文本消息
   * @param receiverAccount 接收人 或者 群组id
   * @param V2NIMConversationType V2NIMConversationType 类型 默认 单聊
   * @returns
   */
  async function sendMessage(
    message: string,
    receiverAccount: string,
    V2NIMConversationType: V2NIMConst.V2NIMConversationType.V2NIM_CONVERSATION_TYPE_P2P = 1
  ) {
    try {
      const msg = nimInstance.V2NIMMessageCreator.createTextMessage(message);
      //'YOUR_ACCOUNT|1|RECEIVER_ACCOUNT' `${nimInfo.value.accountId}|1|${receiverAccount.value}`
      await nimInstance.V2NIMMessageService.sendMessage(
        msg,
        `${nimInfo.value.accountId}|${V2NIMConversationType}|${receiverAccount}`
      );
    } catch (err) {
      console.log(err);
      throw err;
    }
  }

  /**
   * 发送消息给活动的会话
   * @param message
   */
  async function sendMessageBySelectedConversation(message: string) {
    try {
      if (!message) return ElMessage.warning("消息不能为空");
      const store = uikit.context.store;
      const to = store.uiStore.selectedConversation;
      const msg = nimInstance.V2NIMMessageCreator.createTextMessage(message);
      //'YOUR_ACCOUNT|1|RECEIVER_ACCOUNT' `${nimInfo.value.accountId}|1|${receiverAccount.value}`
      const res = await nimInstance.V2NIMMessageService.sendMessage(msg, to);
      // 把当前返回的消息体插入消息列表
      store.msgStore._handleSendMsgSuccess(res.message);
      const messageClientId = res.message.messageClientId;
      // 让消息滚动到可视区域
      document.getElementById(messageClientId).scrollIntoView();
    } catch (err) {
      console.log(err);
    }
  }

  /**
   * 注册绘画监听
   */
  function addConversation() {
    nimInstance.V2NIMLocalConversationService.on("onSyncStarted", () => {
      console.log("onSyncStarted");
    });
    nimInstance.V2NIMLocalConversationService.on("onSyncFinished", () => {
      console.log("onSyncFinished");
    });
    nimInstance.V2NIMLocalConversationService.on("onSyncFailed", (err) => {
      console.log("onSyncFailed", err);
    });
    nimInstance.V2NIMLocalConversationService.on("onConversationCreated", (conversation) => {
      console.log("onConversationCreated创建会话", conversation);
    });
    nimInstance.V2NIMLocalConversationService.on("onConversationDeleted", (conversationIds) => {
      console.log("onConversationDeleted删除会话");
    });
    nimInstance.V2NIMLocalConversationService.on("onConversationChanged", (conversationList) => {
      console.log("onConversationChanged", conversationList);
    });
    nimInstance.V2NIMLocalConversationService.on(
      "onTotalUnreadCountChanged",
      (unreadCount: number) => {
        unreadMessageCount.value = unreadCount;
        console.log("onTotalUnreadCountChanged", unreadCount);
      }
    );
    nimInstance.V2NIMLocalConversationService.on(
      "onUnreadCountChangedByFilter",
      (filter, unreadCount: number) => {
        console.log("onUnreadCountChangedByFilter", filter, unreadCount);
      }
    );
    nimInstance.V2NIMLocalConversationService.on(
      "onConversationReadTimeUpdated",
      (conversationId: string, readTime: number) => {
        console.log("onConversationReadTimeUpdated", conversationId);
      }
    );
  }
  /*移出会话监听*/
  function removeConversation() {
    nimInstance.V2NIMConversationService.off("onSyncStarted");
    nimInstance.V2NIMConversationService.off("onSyncFinished");
    nimInstance.V2NIMConversationService.off("onSyncFailed");
    nimInstance.V2NIMConversationService.off("onConversationCreated");
    nimInstance.V2NIMConversationService.off("onConversationDeleted");
    nimInstance.V2NIMConversationService.off("onConversationChanged");
    nimInstance.V2NIMConversationService.off("onTotalUnreadCountChanged");
    nimInstance.V2NIMConversationService.off("onUnreadCountChangedByFilter");
  }
  /*删除指定单条会话*/
  async function deleteConversation() {
    try {
      await nimInstance.V2NIMConversationService.deleteConversation("CONVERSATION_ID", true);
    } catch (err) {
      console.log(err);
    }
  }
  /*登录*/
  async function login() {
    try {
      await nimInstance.V2NIMLoginService.login(nimInfo.value.accountId, nimInfo.value.token, {
        retryCount: 5,
      });
    } catch (e) {
      console.log("登录失败", e);
    }
  }
  /**
   * 登出函数
   */
  async function logout() {
    try {
      // 尝试调用NIM SDK的登出服务
      await nimInstance.V2NIMLoginService.logout();
      // 登出成功后，重置nimInfo的值，清除本地的登录信息
      nimInfo.value = {
        accountId: "",
        token: "",
      };
    } catch (e) {
      // 登出失败时，打印错误信息并抛出异常
      console.log("登出失败", e);
      throw e;
    }
  }
  /*初始化nim*/
  async function initNim() {
    nimInstance = NIM.getInstance({
      appkey: "9f4e7457146dbcd749a7f7b15b83aabd",
      // 是否开启云端会话，默认不开启
      enableV2CloudConversation: true,
      debugLevel: "debug",
      apiVersion: "v2",
    });
    addConversation();
    nimInstance.V2NIMMessageService.on("onReceiveMessages", function (messages) {
      console.log("收到消息", messages);
      const { fromNick, text } = messages[0];
      /*sendNotification(fromNick, {
        body: text,
      });*/
    });
    nimInstance.V2NIMLoginService.on("onConnectStatus", function (arg1) {
      console.log("登录连接状态变化回调，返回连接状态。", arg1);
    });
    nimInstance.V2NIMLoginService.on("onLoginStatus", function (arg1) {
      console.log("登录状态变化回调，返回变更后的登录状态。", arg1);
    });
  }

  function getInstance() {
    return nimInstance;
  }
  function getUIKit() {
    return uikit;
  }

  function initUiKit() {
    if (uikit) return uikit;
    uikit = new IMUIKit({
      nim: nimInstance,
      singleton: true,
      localOptions,
      renderImDisConnected: () => {
        return "连接失败";
      },
      renderImConnecting: () => {
        return "连接中...";
      },
    });
    return uikit;
  }
  // 请求用户授权通知
  async function requestPermission() {
    if (!("Notification" in window)) {
      ElMessage.error("你的浏览器不支持通知功能");
      return;
    }
    permission.value = await Notification.requestPermission();
  }
  // 发送通知
  function sendNotification(title, options = {}) {
    if (permission.value !== "granted") {
      return;
    }
    const notification = new Notification(title, {
      body: options.body || "",
      icon: options.icon || "/default-icon.png",
    });
    // 监听点击事件
    notification.onclick = (event) => {
      event.preventDefault(); // 防止默认行为（如关闭通知）
      router.push({
        path: "/chat/chatList",
      });
    };
  }

  return {
    getInstance,
    getUIKit,
    initUiKit,
    conversationId,
    nimInfo,
    initNim,
    login,
    sendMessage,
    sendMessageBySelectedConversation,
    messageList,
    receiverAccount,
    getUserInfo,
    getConversationList,
    getChatHistoryList,
    conversationList,
    unreadMessageCount,
    markConversationRead,
    requestPermission,
    sendNotification,
    createTeam,
    getTeamInfo,
    dismissTeam,
    logout,
  };
});
